package com.sky.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.context.BaseContext;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

        @Autowired
        private WorkspaceService workspaceService;

        @Autowired
        private OrderMapper orderMapper;

        @Autowired
        private UserMapper userMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //先计算出开始日期到结束日期过了几天,并将包含的日期保存进集合中
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //从集合中获得每一个日期,并通过日期获取当天的营业额
        //营业额:状态为"已完成"的订单金额合计
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //将LcoalDate格式转换为LocalDateTime,并将开始时间的time部分设置为最小的,结束时间的time部分设置为最大的
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //通过开始时间和结束时间和状态获取当天营业额(打包装入map集合中)
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status",Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            /*if (turnover != null) {//如果查出来没有订单,则直接赋值为0.0
                turnover = 0.0;
            }*/
            turnover = turnover == null ? 0.0 :turnover;
            turnoverList.add(turnover);
        }

        //将集合更改为String类型且每个元素之间以逗号分开
        String joinDate = StringUtils.join(dateList, ",");
        String joinTurnover = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO.builder().dateList(joinDate).turnoverList(joinTurnover).build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        log.info("用户统计");

        //先计算出开始日期到结束日期过了几天,并将包含的日期保存进集合中
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天新增用户数量
        //创建时间得在begin当天的最早时间和最晚时间内
        List<Integer> newUserList = new ArrayList<>();
        //每天总用户数量
        //创建时间在end以内就行
        List<Integer> totalUserList = new ArrayList<>();


        for (LocalDate date : dateList) {
            //beginTime每天的开始时间
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            //endfTime每天的结束时间
            LocalDateTime endfTime = LocalDateTime.of(date,LocalTime.MAX);

            //queryWrapperTotalUser是where部分   where create_time > beginTime
             LambdaQueryWrapper<User> queryWrapperTotalUser = new LambdaQueryWrapper<User>().lt(User::getCreateTime,endfTime);
            Integer totalUser = userMapper.selectCount(queryWrapperTotalUser).intValue();
            totalUserList.add(totalUser);

            //queryWrapperNewUser是where部分   where create_time > beginTime  and  create_time < endTime
            LambdaQueryWrapper<User> queryWrapperNewUser = new LambdaQueryWrapper<User>()
                    .lt(User::getCreateTime,endfTime)
                    .gt(User::getCreateTime,beginTime);
            Integer newUser  = userMapper.selectCount(queryWrapperNewUser).intValue();

            newUserList.add(newUser);
        }



        //将集合更改为String类型且每个元素之间以逗号分开
        String date = StringUtils.join(dateList,",");
        String newUser = StringUtils.join(newUserList, ",");
        String totalUser = StringUtils.join(totalUserList,",");

        return UserReportVO.builder()
                .dateList(date)
                .newUserList(newUser)
                .totalUserList(totalUser)
                .build();

    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        //所有订单
        List<Integer> allOrdersCountList = new ArrayList<>();
        //有效订单
        List<Integer> validOrdersCountList = new ArrayList<>();




        for (LocalDate date : dateList) {
            Map map = new HashMap();
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer allOrders = orderMapper.countByMap(map);
            allOrdersCountList.add(allOrders);
            map.put("status",Orders.COMPLETED);
            Integer validOrders = orderMapper.countByMap(map);
            validOrdersCountList.add(validOrders);
        }

        //使用stream流求和
        Integer totalOrderCount = allOrdersCountList.stream().reduce(Integer::sum).get();
        Integer validOrdersCount = validOrdersCountList.stream().reduce(Integer::sum).get();

        //转换数据格式
        String data = StringUtils.join(dateList, ",");
        String allOrders = StringUtils.join(allOrdersCountList, ",");
        String validOrders = StringUtils.join(validOrdersCountList, ",");

        //计算订单完成率
        //如果总订单数为0,则设置完成率为0,反正报错
        Double orderCompletionRate = 0.0;
            if (totalOrderCount != 0) {
                orderCompletionRate =  validOrdersCount.doubleValue()  / totalOrderCount;
            }


        //封装返回
        return OrderReportVO.builder()
                .dateList(data)
                .orderCountList(allOrders)
                .validOrderCount(validOrdersCount)
                .validOrderCountList(validOrders)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();


    }

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        //转换时间类型
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //多表查询
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        //stream流获取
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //处理数据
        String name = StringUtils.join(nameList, ",");
        String number = StringUtils.join(numberList, ",");

        return SalesTop10ReportVO.builder()
                .nameList(name)
                .numberList(number)
                .build();

    }


    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库,获取营业额数据 --- 查询最近30天的营业数据
        //30天前
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        //昨天
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //获得概览数据
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于末班文件创建新的Excel文件
            XSSFWorkbook execl = new XSSFWorkbook(in);


            //获取表格文件的Sheet页
            XSSFSheet sheet = execl.getSheet("Sheet1");
            //填充数据  --- 时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+dateBegin+"至"+dateEnd);

            //获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获得第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());


            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }

            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            execl.write(out);

            //关闭资源
            out.close();
            execl.close();


        } catch (IOException e) {

        }


        //通过输出流将Excel文件下载到客户端浏览器



    }
}

